var form = layui.form,
    table = layui.table,
    $ = layui.jquery,
    upload = layui.upload,
    id = getQueryVariable("id"),
    sourceType=getQueryVariable("sourceType");


$('#editor-form').find('input,textarea,select').attr('disabled',true);
//表单初始值，修改时调用
if (id != "") {
    form.val("editor-form", {
        "contact": "进入查看明细",
    })
}
if (sourceType == 1){//修改 新建开票
    $("#vendorANDCustomerName").html("厂商名称");
    $("#exportContentANDInvoiceCode").html("报关发票号");
    $("#billingType").html("供应商开票明细");
}else if (sourceType == 2){//修改 客户票
    $("#vendorANDCustomerName").html("客户名称");
    $("#exportContentANDInvoiceCode").html("外销合同号");
    $("#billingType").html("客户开票明细");
}


let billingDetailList=[];
let annexList=[];
layer.ready(function () {

    //获取开票信息
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:id,
        url:"billing/findAllBillingById",
        success:function(res){
            if(res.status == 200){
                $("#code").val(res.data.code);
                $("#contactName").val(res.data.contactName);
                $("#manufacturerName").val(res.data.manufacturerName);
                $("#billingDate").val(res.data.billingDate);
                $("#declarationInvoiceCode").val(res.data.declarationInvoiceCode);
                $("#currencyName").val(res.data.currencyName);
                $("#usdRate").val(res.data.usdRate);
                $("#rmbRate").val(res.data.rmbRate);
                $("#totalInvoicedAmount").val(res.data.totalInvoicedAmount);
                $("#notificationAmount").val(res.data.notificationAmount);
                $("#openedAmount").val(res.data.openedAmount);
                $("#uncommittedAmount").val(res.data.uncommittedAmount);
                $("#createDate").val(res.data.createDate);
                $("#billingTowerHeadName").val(res.data.billingTowerHeadName);
                $("#operatorName").val(res.data.operatorName);
                $("#operatorCode").val(res.data.operatorCode);
                $("#description").val(res.data.description);
                $("#bankName").val(res.data.bankName);
                $("#increaseCode").val(res.data.increaseCode);
                billingDetailList=res.data.billingDetailList;
                annexList=res.data.annexList;

                table.reload('attachmenttableid',{data : annexList});
                table.reload('moaidetailtableid',{data : billingDetailList});
            }
        }

    })
});


//--开票明细
    table.render({
        elem: '#moaidetail',
        id: 'moaidetailtableid',
        data: billingDetailList,
        toolbar: '#moaidetailtoolbar',
        cols: [[

            {field: 'img', title: '图片', width: 120, align: 'center', templet: '#imgTpl'},
            {field: 'saleContractCode', width: 120, title: '销售合同号',sort:true},
            {field: 'stockCode', width: 120, title: '采购单号',sort:true},
            {field: 'goodsCode', width: 120, title: '产品编码',sort:true},
            {field: 'specCode', width: 120, title: '规格编码',sort:true},
            {field: 'goodsSpec', width: 120, title: '规格说明',sort:true},
            {field: 'clientContractNo', width: 120, title: '客户合同号',sort:true},
            {field: 'goodsCname', width: 120, title: '中文名称',sort:true},
            {field: 'goodsEname', width: 120, title: '英文名称',sort:true},
            {field: 'goodsCdesc', width: 120, title: '中文描述',sort:true},
            {field: 'goodsEdesc', width: 120, title: '英文描述',sort:true},
            {field: 'goodsNum', width: 80, title: '数量'},
            {field: 'invoiceUnitPrice', width: 120, title: '开票单价'},
            {field: 'invoiceSubtotal', width: 120, title: '开票小计'},
            {field: 'color', width: 120, title: '颜色'},
            {field: 'goodsGross', width: 120, title: '毛重', sort:true},
            {field: 'totalGross', width: 120, title: '毛重小计', sort:true},
            {field: 'netWeight', width: 120, title: '净重', sort:true},
            {field: 'totalNet', width: 120, title: '净重小计', sort:true},
            {field: 'bulk', width: 120, title: '体积', sort:true},
            {field: 'purchaseUnitPrice', width: 120, title: '采购单价', sort:true},
            {field: 'unitCost', width: 120, title: '成本单价',sort:true},
            {field: 'costSubtotal', width: 120, title: '成本小计',sort:true},
            {field: 'supplyName', width: 120, title: '供应商名称',sort:true},
            {field: 'supplyId', hide:true,title: '供应商ID'},
            {field:'declarePrice', title:'报关单价', width: 120,sort:true},
            {field:'totalPrice', title:'报关金额小计', width: 120,sort:true},
            {field: 'productType', width: 120, title: '产品类型',sort:true},
            {field:'hsCode', title:'海关编码', width: 120,sort:true},
            {field:'billGoodsCname', title:'报关中文品名', width: 140},
            {field:'billGoodsEname', title:'报关英文品名', width: 140},
            {field: 'hsMemo', width: 120, title: '报关要素'},
            {field: 'addRate', width: 120, title: '增值税率'},
            {field: 'backRate', width: 120, title: '退税率'},
            {field: 'goodsUnit', width: 120, title: '单位'},
            {field: 'customerInvoiceGoodsName', width: 120, title: '客户开票货物名称'},
            {field: 'customerInvoiceSpecModel', width: 120, title: '客户开票规格型号'},
            {field: 'customerMaterialsCode', width: 120, title: '客户物料编码'},
        ]],
        page: false,
        limit: Number.MAX_VALUE,
        height: 380
        , done: function (res, curr, count) {
            hoverOpenImg();//显示大图
        }
    });
    function hoverOpenImg() {
        var img_show = null; // tips提示
        $("body").delegate("td img", "mouseover", function () {
            var img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
            img_show = layer.tips(img, this, {
                tips: [2, 'rgba(41,41,41,.5)']
                , area: ['160px']
            });
        });
        $("body").delegate("td img", "mouseout", function () {
            layer.close(img_show);
        });
    }
//监听提交
form.on('submit(form-element)', function (data) {
    //提交到草稿箱
    let reqData=data.field;
    //附件集合
    reqData["annexReqs"] = table.cache["attachmenttableid"];
    //2：修改
    reqData['setType']='2';
    reqData['isViewFile']='isViewFile';//只是用来标记
    reqData['id']=id;
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:JSON.stringify(reqData),
        url:"billing/add/register",
        success:function (res) {
            if(res.status==200){
                layer.msg("保存成功", {icon: 6});
                return false;
            }else {
                layer.msg(res.data, {icon: 6});
                return false;
            }

        }
    });

});
//---附件
table.render({
    elem: '#attachment'
    , data: annexList
    , toolbar: '#attachmenttoolbar'
    , cols: [[
        {field: 'fileName', title: '文件名', fixed: true}
        , {field: 'uploadTime', title: '上传日期', fixed: true}
        , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
    ]]
    , id: 'attachmenttableid'
    , height: 380
    , page: true
});
let uploadListIns = upload.render({
    elem: '#uploadfile'
    , url: 'transfer/uploadFile'
    , field: "uploadify"
    , accept: 'file'
    , multiple: true
    , auto: false
    , bindAction: '#testListAction'
    , choose: function (obj) {
        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
        //读取本地文件
        obj.preview(function (index, file, result) {
            var tr = $(['<tr id="upload-' + index + '">'
                , '<td>' + file.name + '</td>'
                , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                , '<td>等待上传</td>'
                , '<td>'
                , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                , '</td>'
                , '</tr>'].join(''));

            //单个重传
            tr.find('.demo-reload').on('click', function () {
                obj.upload(index, file);
            });

            //删除
            tr.find('.demo-delete').on('click', function () {
                delete files[index]; //删除对应的文件
                tr.remove();
                uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
            });

            $("#uploadlist").append(tr);
        });
    }
    , parseData: function(res){
        return {
            "code": res.status,
            "count": res.total,
            "data": res.data
        };
    }
    , done: function (res, index, upload) {
        let data = res.data;
        for(var i in data){
            if (data[i].status) { //上传成功
                annexList.push(data[i]);
                var tr = $("#uploadlist").find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            this.error(index, upload);
        }
    }
    , error: function (index, upload) {
        var tr = $("#uploadlist").find('tr#upload-' + index)
            , tds = tr.children();
        tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
    }
});
table.on('toolbar(attachmenttable)', function (obj) {
    var checkStatus = table.checkStatus(obj.config.id);
    switch (obj.event) {
        case 'uploadfile':
            $("#uploadlist").html(""); //清空上传列表数据
            layer.open({
                type: 1,
                title: "文件上传",
                area: ['710px', '340px'],
                content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                , cancel: function (index, layero) {
                    table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                }
            });
            break;
    }
    ;
});
table.on('tool(attachmenttable)', function (obj) {
    let data = obj.data;
    if (obj.event === 'download') { //下载
        let xmlHttpRequest = new XMLHttpRequest();
        let url = "wjinfo/downloadfile2?filename=" + data.filePath;
        xmlHttpRequest.open('GET', url, true);
        //设置请求头
        xmlHttpRequest.setRequestHeader("Content-type", "application/json")
        xmlHttpRequest.responseType = "blob";
        xmlHttpRequest.send(null);

        xmlHttpRequest.onload = function() {
            let content = xmlHttpRequest.response;
            // 组装a标签
            let elink = document.createElement("a");

            //设置文件下载路径
            elink.download = decodeURIComponent(data.fileName);
            elink.style.display = "none";
            let blob = new Blob([content], { type: 'application/force-download' });

            //解决下载不存在文件的问题，根据blob大小判断
            if(blob.size==0){
                layer.msg('服务器没找到此文件，请联系管理员!');
            }else{
                elink.href = window.URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                document.body.removeChild(elink);
            }

        }
    } else if (obj.event === 'del') {
        layer.confirm('确认删除?',
            confirmInfo(3,5), function (index) {
                obj.del();
                let id = data.id;
                for (var i = 0; i < annexList.length; i++) {
                    if (annexList[i].id == id) {
                        annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                        i--; // 如果不减，将漏掉一个元素
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
                table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
            });
    }
});
//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}
let data2=[];
//---操作日志
    table.render({
        elem: '#otherwarehouselog'
        , data: data2
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });